'use strict';

import './datePicker.scss';
import React, { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
import {getMDay, weekNumber, addAndDelOneMonth, getDateNow,formatDate} from './dateCore';
import DatePickerBox from './DatePickerBox';
import {offsetTop,offsetLeft} from '../utils/offset';
import {closest} from '../utils/select';

class DatePicker extends Component {

	//默认参数
	static defaultProps = {
		mid : "dateId_"+ new Date().getTime(), //默认box 的 ID
		placeholder:'日期',
		showBack : null, //显示时候的回调
		onChange : null, //关闭时候的回调
		modalClassName : '',
		defaultValue : '',
		format:'yyyy-mm-dd' //格式化
	}
	
	//构造函数
	constructor (props) {
		super(props);
		this.state = {
			show: props.visible,
			set:{
				left:0,
				top:0,
				width:0,
				height:0
			},
			setWeek:['日','一','二','三','四','五','六'],
			nowDate: null,
			date:{
				years:[],
				months:[],
				days:[],
				hours:[],
				minutes:[],
				seconds:[]
			},
			clear:false
		}
		this.div = document.createElement('div');
		this.div.setAttribute('class','mt-div');

		this.firstWeek = 0; //当月第一天是周几
		this.monthDay = 0; //当月有多少天
		this.handlerClickEvent = null;

	}

	//设置初始化的时，分，秒
	setHHMMSS(){
		var hours = [],minutes = [],seconds = [];
		var setArr = function(arr,max){
			for(let i=0; i < max; i++){
				if(i < 10){
					arr.push('0'+i)
				}else{
					arr.push(i.toString())
				}
			}
		}
		setArr(hours,12);
		setArr(minutes,60);
		setArr(seconds,60);

	 	this.setState({
	 		date:{
				years:[],
				months:[],
				days:[],
				hours:hours,
				minutes:minutes,
				seconds:seconds
			}
	 	})     
	}

	//设置days
	setDays(){
		//一共有6*7 = 42 个格子
		let arr = [];
		let date = this.state.nowDate;

		//加一个月
		let addone = addAndDelOneMonth(date.year,date.month,'add');
		if(this.firstWeek == 7){
			for(let i=1; i <= 42; i++){
				if(i <= this.monthDay){
					arr.push({
						day: i,
						month: date.month,
						year: date.year,
						type: 'now',
						active: i === date.day ? true : false
					})
				}else{
					arr.push({
						day: i - this.monthDay,
						month: addone.month,
						year: addone.year,
						type: 'next',
						active: false
					})
				}
			}
		}else{
			//减一个月
			let delone = addAndDelOneMonth(date.year,date.month,'del');
			//获取上个月的日期
			let prevMonth = addAndDelOneMonth(date.year, date.month, 'del').month;
			let prevMonthDay = getMDay(date.year, prevMonth)
			for(let i=1; i <= 42; i++){
				if(i <= this.firstWeek){
					arr.push({
						day: prevMonthDay - this.firstWeek + i,
						month: delone.month,
						year: delone.year,
						type: 'prev',
						active: false
					})
				}else if(i > this.firstWeek && i <= this.monthDay + this.firstWeek){
					arr.push({
						day: i - this.firstWeek,
						month: date.month,
						year: date.year,
						type: 'now',
						active: ( i - this.firstWeek === date.day ) ? true : false
					})
				}else{
					arr.push({
						day: i - this.monthDay - this.firstWeek,
						month: addone.month,
						year: addone.year,
						type: 'next',
						active: false
					})
				}
			}
		}
		return arr;
	}

	//设置month
	setMonths(){
		let arr = []
		for(let i=0; i < 12; i++){
			arr.push({
				active : i+1 === this.state.nowDate.month ? true : false,
				year: this.state.nowDate.year,
				month : i+1
			})
		}
		return arr;
	}

	//重新渲染
	resetDays(date,callback){
		const self = this;
		this.setState({ 
			nowDate: date 
		},function(){
			//当月第一天周几
			self.firstWeek = weekNumber(date.year,date.month,1);
			//当月有多少天
			self.monthDay = getMDay(date.year,date.month);
			//设置days
			let days = self.setDays();
			let months = self.setMonths();
			self.setState({
				date:{
					days:days,
					months:months
				}
			},function(){
				if(callback){
					callback();
				}
			})
		})
	}

	//
	componentWillMount() {

		//init 时 分 秒
		this.setHHMMSS();

		//初始化日期 默认是当前日期
		let date = null;
		if(this.props.defaultValue){
			let val = this.props.defaultValue.split('-');
			date = {
				year : parseInt(val[0], 10),
				month : parseInt(val[1], 10),
				day : parseInt(val[2], 10)
			}
		}else{
			date = getDateNow();
			this.setState({
				clear:true
			})
		}
		this.resetDays(date);
	}

	//渲染div
	renderDiv(){
		var self = this;
		var dom = document.getElementById(this.props.mid);
		//首次渲染即可
		if(!dom){
 			document.body.appendChild(this.div);
			ReactDOM.render(<DatePickerBox resetDays={this.resetDays.bind(this)} {...this.state} showOrHide={this.showOrHide.bind(this)} {...this.props}/>,this.div); //
		}
	}

	componentWillUnmount() {
	 	//document.getElementById(this.props.mid); 
	 	this.div.remove();
        ReactDOM.unmountComponentAtNode(this.div);
	}

	//更新弹窗里面的数据
	componentDidUpdate(prevProps){
		ReactDOM.render(<DatePickerBox resetDays={this.resetDays.bind(this)} {...this.state} showOrHide={this.showOrHide.bind(this)} {...this.props}/>,this.div);
	}

	//隐藏显示
	showOrHide(show,callback,data){
		let box = document.getElementById(this.props.mid);

		//如果没有，初始化一个
		if(!box){
			this.renderDiv();
		}

		this.setState({
			show: !show
		},function(){
			let self = this;
			if(self.state.show){
				if(self.props.showBack){
					self.props.showBack()
				}
			}else{
				if(self.props.onChange && data){
					self.setState({
						clear: data.clear
					})
					
					//数据过滤
					for(let key in data.obj){
						if(data.obj[key]){
							data.obj[key] = parseInt(data.obj[key], 10)
						}else{
							delete data.obj[key];
						}
					}
					data.str = data.str.replace(/-NaN/g,'');
					data.str = data.str.replace(/-undefined/g,'');
					self.props.onChange(data)
				}
			}
			if(callback){
				callback();
			}

			if(show){
				document.removeEventListener('click',self.handlerClickEvent)
			}
		})
	}

	//点击空白隐藏弹窗
	clickBlank(){
		let self = this;
		//通过判断点击的坐标，判断是否点击在弹框内
		let clickInWindow = function(e){
			let set = self.state.set;
			//日历宽 230 * 280
			if(e.clientX >= set.left && e.clientX <= set.left + 230){
				let top = e.clientY + document.body.scrollTop - self.refs.btn.offsetHeight;
				if(top >= set.top && top <= set.top + 280){
					console.log('top')
					return true
				}
			}
			return false
		}

		//点击事件
		this.handlerClickEvent = function(e){
			if(!clickInWindow(e)){
				self.showOrHide(true)
			}
		}
		document.removeEventListener('click',self.handlerClickEvent)
		document.addEventListener('click',self.handlerClickEvent)
	}

	//点击事件
	handleClick(e){
		const self = this;
		//设置set
		this.setState({
			set:{
				left: offsetLeft(self.refs.btn),
				top: offsetTop(self.refs.btn),
				width: self.refs.btn.offsetWidth,
				height: self.refs.btn.offsetHeight
			}
		},function(){
			self.showOrHide(self.state.show);
			//绑定点击空白事件
			self.clickBlank();
		})
	}

	render(){
		var {mid,format,showBack,modalClassName,defaultValue,className,size,...other} = this.props;
		var dayval = formatDate(this.state.nowDate,this.props.format).val;
		var cName = (className?className+' ':'') + 'mt-input-'+(size ? size : 'nm')+ ' mt-input mt-input-date';
		return <span ref="btn" className={cName} onClick={this.handleClick.bind(this)}  >
			<input
			value={this.state.clear?'':dayval} 
			readOnly 
			type="text" 
			placeholder="日期"
			{...other} />
			<span className="mt-input-suffix"><i className="iconfont icon-date"></i></span>
		</span>
	}
}

//主页
export default DatePicker;